package com.example.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DataBaseAdapter {

    // static variables
    static final String DB_NAME = "test.db";
    static final int DB_VERSION = 1;
    public static final int NAME_COLUMN = 1;
    static final String DB_CREATE = "Create Table USER (ID integer primary key autoincrement, "
            + "Username TEXT, Password, TEXT)";

    // variable to hold db instance
    public SQLiteDatabase db;
    // context of app using the db
    private final Context context;
    // db open/upgrade helper
    private DataBaseHelper dbHelper;

    // constructor function
    public DataBaseAdapter(Context _context) {
        context = _context;
        dbHelper = new DataBaseHelper(context, DB_NAME, null, DB_VERSION);
    }

    public DataBaseAdapter open() throws SQLException {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        db.close();
    }

    public SQLiteDatabase getDatabaseInstance() {
        return db;
    }

    public void insertEntry(String userName, String passWord) {
        ContentValues newValues = new ContentValues();
        // assign value for each row
        newValues.put("Username", userName);
        newValues.put("Password", passWord);
        // insert the row into USER table
        db.insert("USER", null, newValues);
    }

    public String getSingleEntry(String userName) {
        Cursor cursor = db.query("USER", null, "Username=?",
                new String[] { userName }, null, null, null);
        if (cursor.getCount() < 1) { // username not exist
            cursor.close();
            return "NOT EXITS";
        }
        cursor.moveToFirst();
        String passWord = cursor.getString(cursor.getColumnIndex("Password"));
        cursor.close();
        return passWord;
    }

}
